package net.wanho.shop.util;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.profile.DefaultProfile;

/**
 * 短信发送工具类
 */
public class SMSUtil {

    private String accessKeyId = "LTAI5tJRTeUeACHXncLUhm9u";
    private String accessKeySecret = "0lK2Ov8Q2YsuOKc3VbkJMJ48XXxXA7";
    private String signName = "商品后台管理系统"; // 签名名称
    private String templateCode = "SMS_477675031"; // 模板CODE

    /**
     * 发送短信
     *
     * @param phoneNumbers 手机号
     * @param param        模板参数
     */
    public void sendMessage(String phoneNumbers, String param) {
        DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, accessKeySecret);
        IAcsClient client = new DefaultAcsClient(profile);

        SendSmsRequest request = new SendSmsRequest();
        request.setSysRegionId("cn-hangzhou");
        request.setSignName(signName);
        request.setTemplateCode(templateCode);
        request.setPhoneNumbers(phoneNumbers);
        request.setTemplateParam("{\"code\":\"" + param + "\"}");
        try {
            SendSmsResponse response = client.getAcsResponse(request);
            System.out.println(JSONObject.toJSONString(response));

            if (!"OK".equals(response.getCode())) {
                throw new RuntimeException("发送验证码失败：" + response.getMessage());
            }
        } catch (ClientException e) {
            throw new RuntimeException("发送验证码失败：" + e.getMessage());
        }
    }
}